<template>
  <div class="dad_box">
    <div class="child1">
      <div class="head1">项目可视化</div>
    </div>

    <div class="child2">
      <div class="chartContainer" ref="chartContainer"></div>
      <div class="chartContainer2" ref="chartContainer2"></div>
    </div>


  </div>
</template>

<script>
import * as echarts from "echarts";
import { getChatData } from "@/api";


export default {
  name: "ManagerChatView",
  data() {
    return {
      projectData: [], // 存储从后端获取的项目数据
    };
  },
  mounted() {
    this.fetchProjectData();
  },
  methods: {
    fetchProjectData() {
      getChatData()
          .then((response) => {
            console.log("Full API response:", response); // 打印完整的响应数据

            if (Array.isArray(response)) {
              this.projectData = response.map((project) => {
                const statusMap = {
                  在途: "inProgress",
                  已过审: "approved",
                  未过审: "rejected",
                  已结项: "completed",
                };
                const newStatus = statusMap[project.projectStatus] || project.projectStatus;

                const newBudget = typeof project.budget === "number" ? project.budget : NaN;
                const newContractAmount = typeof project.contractAmount === "number" ? project.contractAmount : NaN;
                const newCost = typeof project.cost === "number" ? project.cost : NaN;

                return {
                  projectName: project.projectName,
                  budget: newBudget,
                  contractAmount: newContractAmount,
                  cost: newCost,
                  projectStatus: newStatus,
                };
              });

              this.$nextTick(() => {
                this.initChart();
              });
            } else {
              throw new Error("Invalid data format: Expected an array of project objects.");
            }
          })
          .catch((error) => {
            console.error("Error fetching project data:", error);
          });
    },
    countStatus(projectStatus) {
      return this.projectData.filter((item) => item.projectStatus === projectStatus).length;
    },
    initChart() {
      if (!this.projectData.length) {
        console.warn("No project data available to initialize charts.");
        return;
      }

      const chartContainer = this.$refs.chartContainer;
      const chartContainer2 = this.$refs.chartContainer2;

      if (!chartContainer || !chartContainer2) {
        console.error("Chart containers are not found.");
        return;
      }

      const myChart = echarts.init(chartContainer);
      const myChart2 = echarts.init(chartContainer2);

      const xAxisData = this.projectData.map((item) => item.projectName);
      const seriesData1 = this.projectData.map((item) => item.contractAmount - item.cost); // 产值
      const seriesData2 = this.projectData.map((item) => item.cost); // 成本
      const seriesData3 = this.projectData.map((item) => item.contractAmount); // 合同额

      const chartWidth = Math.max(800, xAxisData.length * 50); // 每个项目宽度50像素，最小宽度800
      chartContainer.style.width = chartWidth + "px";

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          data: ["产值", "成本", "合同额"],
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          axisLabel: {
            rotate: 45, // 标签旋转45度
            interval: 0, // 强制显示所有标签
          },
        },
        yAxis: {
          type: "value",
        },
        dataZoom: [
          {
            type: "slider", // 滑动条缩放
            show: true,
            xAxisIndex: 0, // 针对x轴
            start: 0, // 初始展示的百分比范围
            end: 50, // 初始展示的百分比范围
          },
          {
            type: "inside", // 鼠标滚轮缩放
            xAxisIndex: 0,
          },
        ],
        series: [
          {
            type: "bar",
            data: seriesData1,
            name: "产值",
            label: {
              show: true,
              position: "top",
              formatter: "{c}",
            },
          },
          {
            type: "bar",
            data: seriesData2,
            name: "成本",
            label: {
              show: true,
              position: "top",
              formatter: "{c}",
            },
          },
          {
            type: "bar",
            data: seriesData3,
            name: "合同额",
            label: {
              show: true,
              position: "top",
              formatter: "{c}",
            },
          },
        ],
      };

      const option2 = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          x: "left",
        },
        series: [
          {
            name: "项目状态",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "30",
                fontWeight: "bold",
              },
            },
            data: [
              { value: this.countStatus("inProgress"), name: "在途项目" },
              { value: this.countStatus("approved"), name: "通过项目" },
              { value: this.countStatus("rejected"), name: "未通过项目" },
              { value: this.countStatus("completed"), name: "已结项项目" },
            ],
          },
        ],
      };

      myChart.setOption(option);
      myChart2.setOption(option2);
    },
  },
};
</script>

<style>
.dad_box {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 900px;
  margin-bottom: 50px;
}

.child1 {
  height: 20%;
  background-color: rgb(255, 255, 255);
}

.child2 {
  display: flex;
  flex-direction: row;
  height: 75%;
}

.head1 {
  box-sizing: border-box;
  margin-top: 40px;
  margin-left: 40px;
  font-family: Arial;
  text-align: left;
  font-size: 35px;
  color: rgb(51, 51, 51);
  font-weight: 700;
  left: 25px;
}

.chartContainer {
  margin-left: 30px;
  width: 60%;
  height: 100%;
}
.chartContainer2 {
  margin-left: 200px; /* 增加饼图的左边距，向右移动 */
  width: 40%;
  height: 100%;
}
</style>
